﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Globalization;
using System.Security.Cryptography;
using System.IO;

namespace Musicman.Common.Utilities
{
    public static class Converter
    {

        private static CultureInfo MyCi = new CultureInfo("en-US");


        public static string LengthMB(long bytes)
        {
            return LengthMB(bytes, MyCi);
        }

        public static string LengthMB(long bytes, CultureInfo ci)
        {
            float mbLength = (float)bytes / 1048576;
            return String.Format("{0} MB", mbLength.ToString("0.00", ci));
        }

        public static string LengthGB(long bytes)
        {
            return LengthGB(bytes, MyCi);   
        }

        public static string LengthGB(long bytes, CultureInfo ci)
        {
            float mbLength = (float)bytes / 1073741824;
            return String.Format("{0} GB", mbLength.ToString("0.00", MyCi));
        }

        public static string NameTrimmed(string name, int length)
        {
            if (name.Length > length)
            {
                return name.Substring(0, length - 3) + "...";
            }
            else
            {
                return name;
            }
        }

        public static string EncriptPassword(string originalPass)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] originalBytes;
            byte[] encodedBytes;
            originalBytes = ASCIIEncoding.Default.GetBytes(originalPass);
            encodedBytes = md5.ComputeHash(originalBytes);
            return BitConverter.ToString(encodedBytes);
        }

        public static byte[] CreateTumbnail(int width, Stream stream)
        {
            byte[] res = null;
            System.Drawing.Image image = System.Drawing.Image.FromStream(stream);
            float longerSide = image.Width > image.Height ? (float)image.Width : (float)image.Height;
            float aspectRatio = (float)width / longerSide;
            float newSizeX = image.Width * aspectRatio;
            float newSizeY = image.Height * aspectRatio;

            System.Drawing.Bitmap destImage = new System.Drawing.Bitmap((int)newSizeX, (int)newSizeY);
            System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage((System.Drawing.Image)destImage);
            gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            float posX = ((float)width - newSizeX) / 2;
            float posY = ((float)width - newSizeY) / 2;

            gr.DrawImage(image, 0, 0, (int)newSizeX, (int)newSizeY);
            gr.Dispose();
            MemoryStream ms = new MemoryStream();
            destImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            res = ms.ToArray();
            ms.Close();
            return res;
        }
    }
}
